package kz.edu.sdu.atm.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import kz.edu.sdu.atm.models.Request;
import kz.edu.sdu.atm.models.Response;
import kz.edu.sdu.atm.util.Logger;

public class SpeakThread implements Runnable {
	Logger log = new Logger(SpeakThread.class);
	Socket server;
	Request request;
	Response response;
	String host;
	int port;

	public SpeakThread(Request req) {
		request = req;
		host = System.getProperty("atm.host");
		port = Integer.parseInt(System.getProperty("atm.port"));
	}

	public SpeakThread(Request req, String host, int port) {
		request = req;
		this.host = host;
		this.port = port;
	}

	public Response getResponse() {
		return response;
	}

	public void setResponse(Response response) {
		this.response = response;
	}

	@Override
	public void run() {
		try {
			server = new Socket(host, port);
			Scanner in = new Scanner(server.getInputStream());
			PrintWriter out = new PrintWriter(server.getOutputStream());
			ComProtocolClient p = new ComProtocolClient(in, out);
			response = p.speak(request);
			in.close();
			out.close();
			server.close();
		} catch (IOException e) {
			log.error(e.toString());
		} finally {
			if (response != null)
				log.debug("Response is ready!");
		}

	}

}

